package com.yinhai.message.implement.websocket;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * Created by yanglq on 2018/4/3 0003.
 */
public class ChatMessageHandler extends TextWebSocketHandler {

    public static final ConcurrentHashMap<String, WebSocketSession> usersMap = new ConcurrentHashMap<>();
//    private static final ArrayList<WebSocketSession> users;// 这个会出现性能问题，最好用Map来存储，key用userid
    private static Logger logger = LoggerFactory.getLogger(ChatMessageHandler.class);

//    static {
//        users = new ArrayList<WebSocketSession>();
//    }

    /**
     * 连接成功时候，会触发UI上onopen方法
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("connect to the websocket success......");
//        users.add(session);
        String userid = (String)session.getAttributes().get(Constants.WEBSOCKET_USERID);
        if(userid != null){
            usersMap.put(userid,session);
        }
        // 这块会实现自己业务，比如，当用户登录后，会把离线消息推送给用户
        // TextMessage returnMessage = new TextMessage("你将收到的离线");
        // session.sendMessage(returnMessage);
    }

    /**
     * 在UI在用js调用websocket.send()时候，会调用该方法
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String userid = message.getPayload();
        if(userid != null){
            session.getAttributes().put(Constants.WEBSOCKET_USERID,userid);
            usersMap.put(userid,session);
        }
//        sendMessageToUsers(message);
        //super.handleTextMessage(session, message);
    }

    /**
     * 给某个用户发送消息
     *
     * @param userid
     * @param message
     */
    public void sendMessageToUser(String userid, TextMessage message) {
        WebSocketSession user = usersMap.get(userid);
        if(user!=null){
            try {
                if (user.isOpen()) {
                    user.sendMessage(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 给所有在线用户发送消息
     *
     * @param message
     */
    public void sendMessageToAll(TextMessage message) {
        for (Iterator<Map.Entry<String, WebSocketSession>> it = usersMap.entrySet().iterator(); it.hasNext(); ) {
            Map.Entry<String, WebSocketSession> item = it.next();
            WebSocketSession user = item.getValue();
            try {
                if (user.isOpen()) {
                    user.sendMessage(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        if (session.isOpen()) {
            session.close();
        }
        logger.debug("websocket connection closed......");
//        users.remove(session);
        usersMap.remove(session.getAttributes().get(Constants.WEBSOCKET_USERID));
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        logger.debug("websocket connection closed......");
//        users.remove(session);
        usersMap.remove(session.getAttributes().get(Constants.WEBSOCKET_USERID));
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }

}
